import { Controller, Inject, Get, Post, Body, Query } from '@midwayjs/core'
import { RescueInfoService } from '../../service/app/RescueInfoService'
import { BaseController } from '../base.chontroller'

@Controller('/app/rescue-info')
export class RescueInfoController extends BaseController {
  @Inject()
  service!: RescueInfoService

  // 添加帮扶需求
  @Post('/add')
  async addRescueInfo(@Body() data: {
    userId: string
    address: string
    content: string
    img: string[]
    lat: number
    lng: number
    childId: string
  }) {
    // 参数验证
    if (!data?.userId || !data?.address || !data?.content || !data?.childId) {
      return this.fail('缺少必要参数：userId、address、content、childId')
    }

    if (!data.lat || !data.lng) {
      return this.fail('缺少必要参数：lat、lng')
    }

    if (!Array.isArray(data.img)) {
      return this.fail('img参数必须是数组')
    }

    try {
      const result = await this.service.addRescueInfo(data)
      return this.success(result, '添加帮扶需求成功')
    } catch (err: any) {
      return this.fail(err.message || '添加帮扶需求失败')
    }
  }

  // 获取用户的帮扶需求列表
  @Get('/list')
  async getUserRescueInfos(
    @Query('userId') userId?: string,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number
  ) {
    try {
      const data = await this.service.getUserRescueInfos(userId || '0', page || 1, pageSize || 10)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取帮扶需求列表失败')
    }
  }

  // 获取帮扶需求详情
  @Get('/detail')
  async getRescueInfoDetail(@Query('id') id?: number) {
    if (!id) {
      return this.fail('缺少必要参数：id')
    }

    try {
      const data = await this.service.getRescueInfoDetail(id)
      return this.success(data, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取帮扶需求详情失败')
    }
  }

  // 新增帮扶记录
  @Post('/record/add')
  async addRescueRecord(@Body() data: {
    userId: string
    rescueInfoId: number
  }) {
    // 参数验证
    if (!data?.userId || !data?.rescueInfoId) {
      return this.fail('缺少必要参数：userId、rescueInfoId')
    }

    try {
      const result = await this.service.addRescueRecord(data)
      return this.success(result, '添加帮扶记录成功')
    } catch (err: any) {
      return this.fail(err.message || '添加帮扶记录失败')
    }
  }

  // 获取帮扶记录需求信息
  @Get('/record/info')
  async getRescueRecordInfo() {
    try {
      const data = await this.service.getRescueRecordInfo()
      return this.success(data, '获取帮扶记录信息成功')
    } catch (err: any) {
      return this.fail(err.message || '获取帮扶记录信息失败')
    }
  }

}